﻿using Common.Api.Client;
using Common.Api.Dtos;
using Cyss.Core;
using Cyss.Core.Models;
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Pages.Manager.Settings
{
    public partial class SettingDynamicTemplate
    {
        /// <summary>
        /// 类型
        /// </summary>
        [Parameter]
        public SettingTypeModel SettingType { set; get; } = new SettingTypeModel();

        /// <summary>
        /// 是否加载完成
        /// </summary>
        private bool IsLoadComplete { set; get; }

        /// <summary>
        /// 类型键值集合
        /// </summary>
        private List<SettingModel> Models = new List<SettingModel>();

        public override async Task SetParametersAsync(ParameterView parameters)
        {
            bool IsRefresh = true;
            var newSettingType = parameters.GetValueOrDefault<SettingTypeModel>(nameof(this.SettingType));
            if (newSettingType != null || SettingType != null)
            {
                if (newSettingType != null && SettingType != null)
                {
                    if (newSettingType.TypeName != SettingType.TypeName)
                    {
                        IsRefresh = true;
                    }
                }
                else
                {
                    IsRefresh = true;
                }
            }
            await base.SetParametersAsync(parameters);
            if (IsRefresh)
            {
                RefreshData();
            }
        }

        private async void RefreshData()
        {
            if (this.SettingType == null || string.IsNullOrWhiteSpace(this.SettingType.TypeName))
            {
                this.Models.Clear();
                await this.AsyncRefresh();
                return;
            }
            var operateResult = await CommonClientFactory.Setting.GetSettings(this.SettingType.TypeName);
            IsLoadComplete = true;
            if (operateResult.IsSuccess == false)
            {
                await this.Toast(operateResult.Message);
            }
            else
            {
                this.Models = operateResult.Data.ToList();
                await this.AsyncRefresh();
            }

        }

        /// <summary>
        /// 报错
        /// </summary>
        /// <returns></returns>
        private async Task Save()
        {
            var operateResult = await CommonClientFactory.Setting.UpdateSettings(Models);
            if (operateResult.IsSuccess)
            {
                this.SettingType.TypeTitle = this.Models.FirstOrDefault(x => x.PropertyName == nameof(BaseSettingModel.TypeTitle)).PropertyValue;
                await this.AsyncRefresh();
                await this.Alert("保存成功!");
            }
            else
            {
                await this.Alert("保存失败!");
            }
        }
    }
}
